package com.github.netty.holder;

import io.netty.channel.Channel;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author ArchieSean
 * @description netty链接信息缓存
 * @date 2024-08-11
 */
public class NettyHolder {


    /**
     * 用于信道缓存
     */
    public static final ChannelGroup CHANNELS = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    /**
     * 点对点支持：自定义缓存，key: 自定义key，value: channel
     */
    public static  final Map<String, Channel> CHANNEL_MAP = new ConcurrentHashMap<>();

    /**
     * 使用者定义的缓存名称
     */
    public static String CACHE_KEY = "key";

    /**
     * channel的自定义缓存属性对象
     */
    public  static  final AttributeKey<String> ATTR_CACHE_KEY= AttributeKey.valueOf(CACHE_KEY);

    /**
     * 用于从当前channel中获取自定义属性值
     * @param channel 当前信道
     * @return str
     */
    public static  String getCacheKey(Channel channel) {
        return getAttribute(channel,ATTR_CACHE_KEY);
    }

    /**
     * 用于获取channel的自定义属性
     * @return str
     */
    private  static  String getAttribute(Channel channel, AttributeKey<String> key){
        Attribute<String> attr = channel.attr(key);
        return attr.get();
    }



}
